package cn.lisens.demo.web;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.lisens.listener.CustomHttpSessionListener;
import cn.lisens.listener.CustomServletRequestListener;

@RestController
public class ListenerTestController {

	@Autowired
    private CustomHttpSessionListener sessionListener;
    
    @Autowired
    private CustomServletRequestListener requestListener;


    @GetMapping("/stats")
    public Map<String, Object> getStats(HttpServletRequest request) {
        Map<String, Object> stats = new HashMap<>();
        stats.put("activeSessions", sessionListener.getActiveSessionCount());
        stats.put("totalRequests", requestListener.getTotalRequestCount());
        HttpSession session = request.getSession(false);
        stats.putAll(getSessionTimeoutInfo(session));
        return stats;
    }

    @GetMapping("/session")
    public Map<String, Object> testSession(HttpSession session) {
        session.setAttribute("testKey2", "testValue2");
        return getSessionTimeoutInfo(session);
    }
    

    private Map<String, Object> getSessionTimeoutInfo(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        if (session == null) {
            result.put("error", "Session不存在");
            return result;
        }

        long currentTime = System.currentTimeMillis();
        long creationTime = session.getCreationTime();
        long lastAccessedTime = session.getLastAccessedTime();
        int maxInactiveInterval = session.getMaxInactiveInterval();
        long remainingTime = (lastAccessedTime + maxInactiveInterval * 1000L) - currentTime;

        result.put("sessionId", session.getId());
        result.put("creationTime", new Date(creationTime));
        result.put("lastAccessedTime", new Date(lastAccessedTime));
        result.put("maxInactiveInterval", maxInactiveInterval);
        result.put("remainingSeconds", Math.max(0, remainingTime / 1000));
        result.put("remainingTimeFormatted", formatDuration(remainingTime));
        result.put("isNew", session.isNew());

        return result;
    }

    private String formatDuration(long milliseconds) {
        if (milliseconds <= 0) return "已过期";
        
        long seconds = milliseconds / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        
        return String.format("%02d:%02d:%02d", hours, minutes % 60, seconds % 60);
    }
}
